package com.sx.wechat.security;

import com.sx.core.utils.JwtUtils;
import com.sx.core.utils.PropertyUtils;
import com.sx.core.vo.JsonReaderResponse;
import io.jsonwebtoken.Claims;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.oltu.oauth2.common.message.types.ParameterStyle;
import org.apache.oltu.oauth2.rs.request.OAuthAccessResourceRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;


/**
 * TODO: DOCUMENT ME!
 *
 * @author <a href="mailto:lihao@ozstrategy.com">Hao Li</a>
 * @version 07/03/2016 16:16
 */
public class Oauth2Interceptor extends HandlerInterceptorAdapter {
    //~ Instance fields --------------------------------------------------------------------------------------------------



    Log log= LogFactory.getLog(getClass());

    //~ Methods ----------------------------------------------------------------------------------------------------------

    /**
     * @see  HandlerInterceptorAdapter#postHandle(HttpServletRequest,
     *       HttpServletResponse, Object, ModelAndView)
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    //~ ------------------------------------------------------------------------------------------------------------------

    /**
     * @see HandlerInterceptorAdapter#preHandle(HttpServletRequest,
     * HttpServletResponse, Object)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {
        try {

            //构建OAuth资源请求
            OAuthAccessResourceRequest oauthRequest = new OAuthAccessResourceRequest(request, ParameterStyle.HEADER,ParameterStyle.QUERY);
            //获取Access Token
            String accessToken = oauthRequest.getAccessToken();
            Claims claims = JwtUtils.parseJWT(accessToken);

            if(claims.getNotBefore().after(new Date())){
                if(CoreWebUtils.checkAjax(request)){
                    CoreWebUtils.writeJSON(request,response,new JsonReaderResponse("token过期",50000));
                }else{
                    response.sendRedirect(request.getContextPath()+"/403.jsp");
                }
            }

            if(claims!=null){
                RequestContextHolder.getRequestAttributes().setAttribute(Claims.SUBJECT, claims.getSubject(), RequestAttributes.SCOPE_REQUEST);
                RequestContextHolder.getRequestAttributes().setAttribute("access_token", accessToken, RequestAttributes.SCOPE_REQUEST);
            }
            return true;
        } catch (Exception e) {
            log.error("token is wrong>>>>>["+request.getRequestURI()+"]", e);
        }
        if(CoreWebUtils.checkAjax(request)){
            CoreWebUtils.writeJSON(request,response,new JsonReaderResponse("错误的token",50000));
        }else{
            response.sendRedirect(request.getContextPath()+"/403.jsp");
        }
        return false;
    } // end method preHandle


} // end class MemberInterceptor
